package controller;

import remoteEntity.Category;
import remoteEntity.User;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import manager.FileManager;
import org.primefaces.model.UploadedFile;

/**
 * FileUploadController
 *
 * JSF Managed backing bean containing logic for handling file uploads.
 */
@ManagedBean
@RequestScoped
public class FileUploadController {

    @EJB
    private FileManager fileManager;
    private String name;
    private String description;
    private UploadedFile file;
    private int category;

    public int getCategory() {
        return category;
    }

    public void setCategory(int category) {
        this.category = category;
    }

    public List<Category> getCategories() {
        return fileManager.getAllCategories();
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public void upload() {
        try {
            int id = copyFile(file.getInputstream());
            this.name = this.description = null;
            this.category = 0;
            FacesMessage msg = new FacesMessage(file.getFileName() + " successfully uploaded.");
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, msg);

            FacesContext.getCurrentInstance().
                    getExternalContext().redirect("fileinfo?id=" + id);
        } catch (IOException e) {
            FacesMessage msg = new FacesMessage("Could not upload " + file.getFileName());
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (Exception e) {
            FacesMessage msg = new FacesMessage("Please fill all fields");
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        try {
            this.description = new String(description.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        try {
            this.name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        } catch (Exception e) {
        }
    }

    private int copyFile(InputStream in) {
        try {
            // 16 kb read buffer
            int BYTEARRAYSIZE = 16384;

            InputStream is = in;
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();

            int nRead;
            byte[] data = new byte[BYTEARRAYSIZE];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            UserController lb = (UserController) FacesContext.getCurrentInstance().getExternalContext().
                    getSessionMap().get("userController");
            User user = lb.getUser();

            return fileManager.addFile(buffer.toByteArray(), this.name,
                    this.description, this.category, user);

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return 0;
    }
}
